//
//  TKYProgressDateController.m
//  StationHouseHelper
//
//  Created by apple on 2018/7/16.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYProgressDateController.h"
#import "BRPickerView.h"
#import "TKYSettingCell.h"
#import "TKYDateIntervalController.h"

#define kSettingCellID @"TKYSettingCell"
@interface TKYProgressDateController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UIDatePicker *datePicker;

@property (nonatomic, strong)BaseTabelView  *tabelView;


@property (nonatomic, strong)TKYSettingCell *cell;

/**距离现在的时间*/
@property (nonatomic, strong)UILabel *awayNowDateLabel;

@property (nonatomic, strong)NSString *dateSelectedStr;

@property (nonatomic, strong)NSDate *date;

@property (nonatomic, strong) UILocalNotification *localNotification;

@end

@implementation TKYProgressDateController

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.awayNowDateLabel.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self.tabelView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
}

//设置界面
- (void)setupUI{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"进度提醒设置";
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    //返回
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_btn"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonItemAction:)];
    //保存
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(saveBarButtonItemAction:)];
    
    [self.view addSubview:self.tabelView];
    self.tabelView.tableHeaderView = self.datePicker;
    [[UIApplication sharedApplication].keyWindow addSubview:self.awayNowDateLabel];
}

//返回
- (void)backBarButtonItemAction:(UIBarButtonItem *)barButtonItem{
    [self.navigationController popViewControllerAnimated:YES];
}

//保存
- (void)saveBarButtonItemAction:(UIBarButtonItem *)barButtonItem{
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedDateStr"];
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"selectedDateStr"]);
    if (str.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择提前几分钟" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    //保存用户通知信息
    //[self requestSaveMessageInfo];
    //发送通知
    [self createLocalNotification];
    [self.navigationController popViewControllerAnimated:YES];
}


/**保存用户通知信息*/
- (void)requestSaveMessageInfo{
    NSString *url = [NSString stringWithFormat:@"%@%@",kApiBaseUrl,KsaveMessageInfoURL];
    NSDictionary *paramertDict = @{
                                   @"token":[[NSUserDefaults standardUserDefaults]objectForKey:kToken],
                                   @"projectId":[[NSUserDefaults standardUserDefaults]objectForKey:KStationHouseID],
                                   @"remindUser":[[NSUserDefaults standardUserDefaults] objectForKey:KUSERNAMEKEY]
                                   };
    [KHttpRequestTool POST:url parameters:paramertDict success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        }else{
            [SVProgressHUD showErrorWithStatus:response[@"msg"]];
        }
        
    } failure:^(NSError *error) {
         [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

#pragma mark --创建本地通知
- (void)createLocalNotification{
    //创建之前销毁旧
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    self.localNotification = nil;
    // 1.创建通知
    self.localNotification = [[UILocalNotification alloc] init];
    //2.设置通知的必选参数
    //设置通知显示的内容
    self.localNotification.alertBody =[NSString stringWithFormat:@"还有%@就该填写日报了",[[NSUserDefaults standardUserDefaults] objectForKey:@"selectedDateStr"]] ;
    // 设置通知的发送时间,单位秒7*60*60
    self.localNotification.fireDate = self.date ;
    //自行设定间
    self.localNotification.repeatInterval = NSCalendarUnitDay;
    //解锁滑动时的事件
    self.localNotification.alertAction = @"填报!";
    //收到通知时App icon的角标
    //应用图标提示--默认是0,没有改变,设置为负数,通知到达时图标提示就会消失
    self.localNotification.applicationIconBadgeNumber = -1;
    //直接设置应用图标提示为0,代表隐藏,和上面效果一致
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    //推送是带的声音提醒，设置默认的字段为UILocalNotificationDefaultSoundName
    self.localNotification.soundName = UILocalNotificationDefaultSoundName;
    self.localNotification.userInfo = @{@"localNotification":@"localNotifi"};
    [[UIApplication sharedApplication] scheduleLocalNotification:self.localNotification];
}

- (void)dateChange:(UIDatePicker *)datePicker
{
    NSDate *theDate = datePicker.date;
    NSLog(@"%@",[theDate descriptionWithLocale:[NSLocale currentLocale]]);
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    
    NSString * dateStr = [dateFormatter stringFromDate:theDate];
    
    [[NSUserDefaults standardUserDefaults ]setObject:dateStr forKey:@"dateStr"];
    NSLog(@"%@",[dateFormatter stringFromDate:theDate]);
    
    //获取到的时间戳
    NSInteger dateInt= [self getTimeStrWithString :dateStr];
    //当前的时间
    NSLog(@"%ld",[self getNowTimestamp]);
    //时间差
    NSInteger dateI;
    NSInteger dateLocal;//本地推送通知的时间
    if (dateInt < [self getNowTimestamp]) {//第二天
        dateI = ((dateInt -[self getNowTimestamp])) + 24*3600;
        dateLocal = dateInt + 24*3600;
    }else{//今天
        dateI = (dateInt -[self getNowTimestamp]);
        dateLocal = dateInt;
    
    }
    //取出保存的提前多久可以发送通知
     NSString *selectedDateStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedDateStr"];
    if ([selectedDateStr isEqualToString:@"1分钟"]) {
        dateLocal = dateInt - 60;
    }else if ([selectedDateStr isEqualToString:@"2分钟"]){
        dateLocal = dateInt - 120;
    }else if ([selectedDateStr isEqualToString:@"5分钟"]){
        dateLocal = dateInt - 300;
    }else if ([selectedDateStr isEqualToString:@"10分钟"]){
        dateLocal = dateInt - 600;
    }
    
    NSString *str = [self getDateStringWithTimeInteger:dateLocal];;
    // 日期格式化类
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    
    // 设置日期格式 为了转换成功
    format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    // NSString * -> NSDate *
    NSDate *date = [format dateFromString:str];
    self.date = date;
    self.dateSelectedStr = str;
    
   // dateI  = 3680;
    self.awayNowDateLabel.text = @"";
    NSLog(@"%.ld,%ld,%ld ",dateI/3600,dateI%3600/60,dateI%3600%60);
    if ( self.awayNowDateLabel.text.length == 0) {
         self.awayNowDateLabel.text = [NSString stringWithFormat:@"%ld小时%ld分钟%ld秒后提醒 ",dateI/3600,dateI%3600/60,dateI%3600%60];
    }
}
#pragma mark-- UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.cell = [tableView dequeueReusableCellWithIdentifier:kSettingCellID];
    self.cell.titleLabel.text = @"提醒频率";
    self.cell.isTouch = YES;

    self.cell.contentLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedDateStr"];
    return self.cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TKYDateIntervalController *dateIntervalVC = [[TKYDateIntervalController alloc]init];
    self.cell.contentLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedDateStr"];
    [self.navigationController pushViewController:dateIntervalVC animated:YES];
}

- (UIDatePicker *)datePicker{
    if (_datePicker == nil) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0,0,kScreenWidth,kHeightScale *300)];
        _datePicker.datePickerMode = UIDatePickerModeTime;
        _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
        [_datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _datePicker;
}

- (BaseTabelView *)tabelView{
    if (_tabelView == nil) {
        _tabelView = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _tabelView.delegate = self;
        _tabelView.dataSource = self;
        
        [_tabelView registerClass:[TKYSettingCell class] forCellReuseIdentifier:kSettingCellID];
        _tabelView.tableFooterView = [[UIView alloc]init];
    }
    return _tabelView;
}


//获取当前时间戳
-(NSInteger)getNowTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    NSLog(@"设备当前的时间:%@",[formatter stringFromDate:datenow]);
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    NSLog(@"设备当前的时间戳:%ld",(long)timeSp); //时间戳的值
    return timeSp;
    
}

//将某个时间转化成 时间戳
#pragma mark - 将某个时间转化成 时间戳
//字符串转时间戳 如：2017-4-10 17:15:10
- (NSInteger )getTimeStrWithString:(NSString *)str{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSInteger timeStr = [[NSNumber numberWithDouble:[tempDate timeIntervalSince1970]] integerValue];;//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}

// 时间戳转时间,时间戳为13位是精确到毫秒的，10位精确到秒
- (NSString *)getDateStringWithTimeInteger:(NSInteger )integer{
    //NSTimeInterval time=[str doubleValue];//传入的时间戳str如果是精确到毫秒的记得要/1000
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:integer];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}

- (UILabel *)awayNowDateLabel{
    if (_awayNowDateLabel == nil) {
        _awayNowDateLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidthScale *10, MyNavBarHeight, kScreenWidth- kWidthScale *20, kHeightScale *20)];
        _awayNowDateLabel.textAlignment = NSTextAlignmentCenter;
        _awayNowDateLabel.font = Font(14);
    }
    return _awayNowDateLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
